$(function(){
    //统计图表切换
    $('#chartTab').on('click', 'li', function(){
        var current = $(this).attr('class');
        var param = $(this).attr('data-id');
        if(!current){
            $(this).addClass('active').siblings().removeClass('active');
            $('.chart-cont .chartbox').hide().eq($(this).index()).show();
        }
    });
    //当天统计折线图
    var dayLine = echarts.init(document.getElementById('dayLine'));
    var dayLineOption = {
        tooltip: {
            trigger: 'axis',
            formatter: "识别：{c}张"
        },
        grid: {
            left: '45',
            right: '45',
            top: '45',
            bottom: '0',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            name:'今天',
            axisLine: {show: false},
            axisTick: {show: false},
            boundaryGap: false,
            data: []

        },
        yAxis: {
            type: 'value',
            name:"张",
            minInterval: 1,
            axisLine: {show: false},
            axisTick: {show: false}
        },
        series: [
            {
                name: '各小时识别的数量',
                type: 'line',
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                        color: '#44a8e4'
                    }
                },
                data:[]
            }
        ]
    }
    dayLine.showLoading();
    util.ajaxget1(util.url+"/hbase/getDayCountData/"+util.tablename,function (data) {
        dayLineOption.xAxis.data=data.x;
        dayLineOption.series[0].data=data.y;
        dayLine.setOption(dayLineOption);
        dayLine.hideLoading();
    },function (data) {
        dayLine.hideLoading();
    });

    //本周统计折线图
    var weekLine = echarts.init(document.getElementById('weekLine'));
    var weekLineOption = {
        tooltip: {
            trigger: 'axis',
            formatter: "识别：{c}张"
        },
        grid: {
            left: '45',
            right: '45',
            top: '45',
            bottom: '0',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            name:'本周',
            axisLine: {show: false},
            axisTick: {show: false},
            boundaryGap: false,
            data: [1,2,3,4,5,6,7]

        },
        yAxis: {
            type: 'value',
            name:"张",
            minInterval: 1,
            axisLine: {show: false},
            axisTick: {show: false}
        },
        series: [
            {
                name: '本周每天识别的数量',
                type: 'line',
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                        color: '#44a8e4'
                    }
                },
                data:[105,180,200,380,460,100,200]
            }
        ]
    }
    weekLine.showLoading();
    util.ajaxget1(util.url+"/hbase/getWeekCountData/"+util.tablename,function (data) {
        weekLineOption.xAxis.data=data.x;
        weekLineOption.series[0].data=data.y;
        weekLine.setOption(weekLineOption);
        weekLine.hideLoading();
    },function (data) {
        weekLine.hideLoading();
    });
    //本月统计折线图
    var monthLine = echarts.init(document.getElementById('monthLine'));
    var monthLineOption = {
        tooltip: {
            trigger: 'axis',
            formatter: "识别：{c}张"
        },
        grid: {
            left: '45',
            right: '45',
            top: '45',
            bottom: '0',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            name:'本月',
            axisLine: {show: false},
            axisTick: {show: false},
            boundaryGap: false,
            data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]

        },
        yAxis: {
            type: 'value',
            name:"张",
            minInterval: 1,
            axisLine: {show: false},
            axisTick: {show: false}
        },
        series: [
            {
                name: '本月每天识别的数量',
                type: 'line',
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                        color: '#44a8e4'
                    }
                },
                data:[105,180,200,380,460,100,200,65,90,80,20,2,25,6,14,78,96,32,58,65,54,51,52,62,63,25,15,19,90,22]
            }
        ]
    }
    monthLine.showLoading();
    util.ajaxget1(util.url+"/hbase/getMonthCountData/"+util.tablename,function (data) {
        monthLineOption.xAxis.data=data.x;
        monthLineOption.series[0].data=data.y;
        monthLine.setOption(monthLineOption);
        monthLine.hideLoading();
    },function (data) {
        monthLine.hideLoading();
    });


    util.ajaxget1(util.url+"/hbase/Count2/"+util.tablename,function (data) {
        $('.zti2').text(data.allCount);
        $('.zti3').text(data.rightCount);
        $('.zti1').text(data.rightPercent);
        //正确率
        var c = $('#processingbar');
        var a = data.rightPercent.replace(/\%/, '');
        animateEle(c,a);
    },function (data) {
    });




    //根据时间切换
    $('#tabTIme').on('click', 'li', function(){

        var param = $(this).attr('data-id');
        var current = $(this).attr('class');

        if(!current){
            $(this).addClass('active').siblings().removeClass('active');
            $('#timezone').val(param);
            if(param!=9){
                $("#currentPage").val(1);//切换时重置当前页
                initTable(true);
            }
         }
        if(param==9){
            layui.laydate.render({
                elem: document.getElementById('zdy')
                ,type: 'datetime'
                ,range: '~'
                ,theme: '#44a8e4'
                ,show:true
                ,closeStop: document.getElementById('zdy1') //这里代表的意思是：点击所在元素阻止关闭事件冒泡。如果不设定，则无法弹出控件
                //,position:'fixed'
                ,done: function(value, date, endDate){
                    if(value.length>5){
                        //alert(value)
                        $("#zdy").val(value);
                        $("#currentPage").val(1);//切换时重置当前页
                        initTable(false);
                    }
                }
            });
        }


    });

    //根据结果切换
    $('#tabResult').on('click', 'li', function(){
        var current = $(this).attr('class');
        var param = $(this).attr('data-id');
        if(!current){
            $(this).addClass('active').siblings().removeClass('active');
            $('#reresult').val(param);
            $("#currentPage").val(1);//切换时重置当前页
            var f=true;
            if($("#timezone").val()==9){
                f=false;
            }
            initTable(f);
        }
    });
	//导出结果
    $('#export').on('click', function(){
    	if(parseInt($("#recordcount").text())>65000){
            layui.layer.msg('一次导出的数量不能超过65000', {time: 3000, icon:5});
		}else {
            var f=true;
            if($("#timezone").val()==9){
                f=false;
            }
            if(f) {
                window.open(util.url + "/hbase/ExportDetailData/" + util.tablename + "/" + $("#timezone").val() + "/" + $("#reresult").val());
            } else{
                var starttime=Date.parse(new Date($("#zdy").val().split('~')[0].replace(/-/g,"/")));
                var endtime=Date.parse(new Date($("#zdy").val().split('~')[1].replace(/-/g,"/")));
                window.open(util.url + "/hbase/ExportDetailDataByTime/" + util.tablename + "/" + starttime+"/"+endtime + "/" + $("#reresult").val());
            }
        }
    });
    //导出图片
    $('#exportpic').on('click', function(){
        if(parseInt($("#recordcount").text())>5000){
            layui.layer.msg('一次导出的数量不能超过5000', {time: 3000, icon:5});
        }else {
            var f=true;
            if($("#timezone").val()==9){
                f=false;
            }
            if(f) {
                window.open(util.url+"/hbase/ExportPicData/"+util.tablename+"/"+$("#timezone").val()+"/"+$("#reresult").val());
            } else{
                var starttime=Date.parse(new Date($("#zdy").val().split('~')[0].replace(/-/g,"/")));
                var endtime=Date.parse(new Date($("#zdy").val().split('~')[1].replace(/-/g,"/")));
                window.open(util.url+"/hbase/ExportPicDataByTime/"+util.tablename+"/"+starttime+"/"+endtime+"/"+$("#reresult").val());
            }
        }
    });

    initTable(true);
});
/**
 * @param source 查询行为的来源 
 */
function getChartsList(count){
    //初始化分页组件
    var laypage = layui.laypage;
    laypage.render({
        elem: 'paging'
        ,count:count
        ,limit: parseInt($("#pageSize").val())
        ,limits:[10, 20, 30]
        ,layout:['prev', 'page', 'next','limit']
        ,theme: '#44a8e4'
        ,jump: function(obj, first){
            //首次不执行
            if(!first){
                var f=true;
                if($("#timezone").val()==9){
                    f=false;
                }
                if(obj.limit==$("#pageSize").val()){
                    $("#currentPage").val(obj.curr);
                    createTable("tbody",f);
                }else {
                    $("#currentPage").val(1);
                    $("#pageSize").val(obj.limit);
                    initTable(f);
                }

            }

        }
    });


}

function initTable(flag) {
    if(flag){
        util.ajaxget1(util.url+"/hbase/getDataCount/"+util.tablename+"/"+$("#timezone").val()+"/"+$("#reresult").val(),function (data) {
            $("#recordcount").text(data);
            getChartsList(data);
            createTable("tbody",flag);
        },function (data) {
        });

    }else {
        //获取起止时间
        var starttime=Date.parse(new Date($("#zdy").val().split('~')[0].replace(/-/g,"/")));
        var endtime=Date.parse(new Date($("#zdy").val().split('~')[1].replace(/-/g,"/")));
        util.ajaxget1(util.url+"/hbase/getDataCountByTime/"+util.tablename+"/"+starttime+"/"+endtime+"/"+$("#reresult").val(),function (data) {
            $("#recordcount").text(data);
            getChartsList(data);
            createTable("tbody",flag);
        },function (data) {
        });
    }

}

function createTable(id,flag) {
    var layindex = layui.layer.load(1);
    if(flag){
    util.ajaxget1(util.url+"/hbase/getDetailData/"+util.tablename+"/"+$("#timezone").val()+"/"+$("#reresult").val()+"/"+$("#currentPage").val()+"/"+$("#pageSize").val(),function (data) {
            createtabledetail(id,data);
            layui.layer.close(layindex);
        },
        function(){
            layui.layer.close(layindex);
        }
    );
    }else{
        var starttime=Date.parse(new Date($("#zdy").val().split('~')[0].replace(/-/g,"/")));
        var endtime=Date.parse(new Date($("#zdy").val().split('~')[1].replace(/-/g,"/")));
        util.ajaxget1(util.url+"/hbase/getDetailDataByTime/"+util.tablename+"/"+starttime+"/"+endtime+"/"+$("#reresult").val()+"/"+$("#currentPage").val()+"/"+$("#pageSize").val(),function (data) {
                createtabledetail(id,data);
                layui.layer.close(layindex);
            },
            function(){
                layui.layer.close(layindex);
            }
        );

    }
}

function createtabledetail(id,data) {
    $("#"+id).empty();
    for(var i=0;i<data.length;i++){
        var itemdata=data[i];
        if(itemdata.cf1.result&&itemdata.cf1.result.length>3){
            var rect=JSON.parse(itemdata.cf1.result)[0].rect;
            if(rect.x==0&&rect.y==0&&rect.w==0&&rect.h==0){
                var shibiejieguo=JSON.parse(itemdata.cf1.result)[0].numReading;
                var jiaoyanjieguo= itemdata.cf1.actualReading?itemdata.cf1.actualReading:"暂无";
                var item="<tr><td>"+timeStamp2String(itemdata.cf1.timestamp)+"</td><td><a href='javascript:showBigImg("+i+");'>识别错误</a></td><td>"+shibiejieguo+"</td><td>"+jiaoyanjieguo+"</td><td style='display: none'><img id='bigimg"+i+"'src="+itemdata.cf1.imgContent+"></td></tr>";
            }else{
                var shibiejieguo=JSON.parse(itemdata.cf1.result)[0].numReading;
                var jiaoyanjieguo=itemdata.cf1.actualReading?itemdata.cf1.actualReading:"正确";
                var item="<tr><td>"+timeStamp2String(itemdata.cf1.timestamp)+"</td><td><img id='smallimg"+i+"' onclick='showBigImg("+i+")' style='width: 250px;height: 40px'/></td><td>"+shibiejieguo+"</td><td>"+jiaoyanjieguo+"</td><td style='display: none'><img id='bigimg"+i+"'src="+itemdata.cf1.imgContent+" crossOrigin='anonymous'></td></tr>";
                cropimg(itemdata.cf1.imgContent,rect,'smallimg'+i);
            }

        }else{
            var shibiejieguo='未识别';
            var jiaoyanjieguo= itemdata.cf1.actualReading?itemdata.cf1.actualReading:"暂无";
            var item="<tr><td>"+timeStamp2String(itemdata.cf1.timestamp)+"</td></tr>";
        }
        $("#"+id).append(item);
    }
}
function showBigImg(i) {
    $('#mmm').removeAttr("src");
    $('#mmm').attr("src",$("#bigimg"+i)[0].src);
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: ['800px', '600px'],
            //skin: 'layui-layer-nobg', //没有背景色
            end:function () {
                $('#mmm').hide();
            },
            shadeClose: true,
            content: $('#mmm')
        });

    layui.layer.photos({
        photos: '#bigimg'+i
        ,closeBtn:1
        //,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

function timeStamp2String (time){
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1;
    var date = datetime.getDate();
    var hour = datetime.getHours();
    var minute = datetime.getMinutes();
    var second = datetime.getSeconds();
    var mseconds = datetime.getMilliseconds();
    return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
};
function cropimg(imgContent,rect,imgid) {
    var image =  new Image();
    image.addEventListener("load",function() {
        var c=document.createElement('canvas');
        var ctx=c.getContext("2d");
        c.width = image.width;
        c.height = image.height;
        ctx.drawImage(image, 0, 0);
        var c1=document.createElement('canvas');
        var ctx1=c1.getContext("2d");
        var imgdata=ctx.getImageData(rect.x, rect.y, rect.w, rect.h);
        c1.width = imgdata.width;
        c1.height = imgdata.height;
        ctx1.putImageData(imgdata,0,0);
        document.getElementById(imgid).src=c1.toDataURL("image/jpeg");

    },false);
    image.src=imgContent;
}

